文章目录

初始化一个不可变map,我们常常的做法是用修饰符“static final”;如下代码所示,
然而事实是初始化过后,我们人然可以继续操作该map,比如:Test.map.put(3,”Three”);
所以,这样的方法并没有真正的达到我们的要求。

1
2
3
4
5
6
7
8
9
//code 1
public class Test {
private static final Map map;
static {
map = new HashMap();
map.put(1, "one");
map.put(2, "two");
}
}

下面的代码在初始化最后用:Collections.unmodifiableMap() 来处理,如果此时试图添加元素会抛出
“UnsupportedOperationException”异常。

1
2
3
4
5
6
7
8
9
10
//code 2
public class Test {
private static final Map map;
static {
Map aMap = new HashMap();
aMap.put(1, "one");
aMap.put(2, "two");
map = Collections.unmodifiableMap(aMap);
}
}
文章目录